package cn.wuxing.mediation.businessplatform.service.impl;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

/**
 * @description: <描述>
 * @date: 2024/9/23 21:38
 * @author: yang
 * @version: 1.0
 */
public class Test {


    public static void main(String[] args) throws Exception {
        XWPFDocument xwpfDocument = loadTemplate("D:\\temporaryoffice\\Test.docx");
        replacePlaceholders(xwpfDocument,
                Arrays.asList("订单1", "订单2", "订单3"));

        exportDocument(xwpfDocument, "D:\\temporaryoffice\\output.docx");
    }

    public static XWPFDocument loadTemplate(String path) throws Exception {
        // 加载Word模板
        return new XWPFDocument(Files.newInputStream(Paths.get(path)));
    }

    public static void replacePlaceholders(XWPFDocument document, List<String> orderList) {
        // 创建一个字符串构建器来存储订单信息
        StringBuilder orders = new StringBuilder();
        for (String order : orderList) {
            orders.append(order).append("\n"); // 循环处理订单信息
        }

        // 替换占位符
        for (XWPFParagraph paragraph : document.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                String text = run.getText(0);
                if (text != null && text.contains("{{orderList}}")) {
                    text = text.replace("{{orderList}}", orders.toString());
                    run.setText(text, 0); // 替换文本
                }
            }
        }
    }

    public static void exportDocument(XWPFDocument document, String outputPath) throws Exception {
        // 导出生成的文档
        FileOutputStream out = new FileOutputStream(outputPath);
        document.write(out);
        out.close();
    }
}
